import axios from 'axios'
import { message } from 'antd';
import { createBrowserHistory } from 'history'
import { getToken } from './token.js'
import { store } from '../Store/index.js';

const history = createBrowserHistory();

// 默认配置
const request = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/api' : ''
})



// 请求拦截器
request.interceptors.request.use(
  function (config) {
    if (getToken()) {
      // 请求头+token
      // config.headers['X-Token'] = JSON.stringify(getToken())
      if (config.method === 'post') {

      }
      if (config.method === 'get') {
        // config.params.token = getToken()
      }
    }
    // loading显示
    store.dispatch({
      type: "CHANGE_LOADING",
      payload: true
    })
    return config
  },
  function (error) {
    // loading隐藏
    store.dispatch({
      type: "CHANGE_LOADING",
      payload: false
    })
    console.log(getToken(), 'getToken()');

    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    // loading隐藏
    store.dispatch({
      type: "CHANGE_LOADING",
      payload: false
    })
    // 判断当前请求是否设置了不显示Loading
    const errCode = [401, 403];
    if (errCode.includes(response.data.code)) {
      // 弹出错误提醒 清除缓存 跳转到登录页
      message.error('登录状态失效或者过期，请重新登录', 2, () => {
        // 清缓存
        localStorage.removeItem('token');
        localStorage.removeItem('useInfo');
        // 到登录页
        history.push('/login');
        history.go(0);
      })
    }
    return response
  },
  function (error) {
    // loading隐藏
    store.dispatch({
      type: "CHANGE_LOADING",
      payload: false
    })
    return Promise.reject(error)
  }
)

export default request
